package com.sk.weichat.ui.me;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.hlg.yueliao.wxapi.WXEntryActivity;
import com.sk.weichat.R;
import com.sk.weichat.bean.LoginRegisterResult;
import com.sk.weichat.db.dao.UserDao;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.ui.account.BandAndChangePhoneActivity;
import com.sk.weichat.ui.account.SetPasswordActivity;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.util.Constants;
import com.sk.weichat.util.StringUtils;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.util.UiUtils;
import com.tencent.connect.UserInfo;
import com.tencent.connect.auth.QQToken;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;
import com.xuan.xuanhttplibrary.okhttp.result.Result;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

/**
 * 设置
 */
public class SettingSafetyActivity extends BaseActivity implements View.OnClickListener {

    private TextView mTvWechat;
    private TextView mTvQQ;
    private Tencent mTencent;
    private BaseUiListener mIUiListener;
    private TextView mTvPhone;
    private TextView mTvPassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting_safety);
        getSupportActionBar().hide();

        //腾讯QQ登录初始化
        if (mTencent == null) {
            mTencent = Tencent.createInstance(Constants.QQ_APP_ID, this.getApplicationContext());
        }


        mTvPassword=(TextView)findViewById(R.id.tv_safety_password);
        mTvPhone=(TextView)findViewById(R.id.tv_safety_phone);
        mTvWechat=(TextView)findViewById(R.id.tv_safety_wechat);
        mTvQQ=(TextView)findViewById(R.id.tv_safety_qq);

        updateUI();

        findViewById(R.id.iv_title_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        TextView tvTitle = (TextView) findViewById(R.id.tv_title_center);
        tvTitle.setText(getString(R.string.setting_safety));

        initView();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(com.sk.weichat.broadcast.OtherBroadcast.SEND_MULTI_NOTIFY);
        intentFilter.addAction(com.sk.weichat.broadcast.OtherBroadcast.NO_EXECUTABLE_INTENT);
    }

    @Override
    protected void onResume() {
        super.onResume();
        updateUI();
    }

    private void updateUI() {
        if(coreManager.getSelf().getHavePassword()== 0){
            mTvPassword.setText(getString(R.string.hint_password));
        }else{
            mTvPassword.setText(getString(R.string.change_password));
        }

        mTvPhone.setText(StringUtils.hiddenPhone(coreManager.getSelf().getPhone()));

        if(coreManager.getSelf().getIsWXBand()==0){
            mTvWechat.setText("未绑定");
        }else{
            mTvWechat.setText(coreManager.getSelf().getWxNikeName());
        }

        if(coreManager.getSelf().getIsQQBand()==0){
            mTvQQ.setText("未绑定");
        }else{
            mTvQQ.setText(coreManager.getSelf().getQqNickName());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    private void initView() {
        findViewById(R.id.layout_device_lock).setOnClickListener(this);
        findViewById(R.id.layout_safety_password).setOnClickListener(this);
        findViewById(R.id.layout_safety_phone).setOnClickListener(this);
        findViewById(R.id.layout_safety_wechat).setOnClickListener(this);
        findViewById(R.id.layout_safety_qq).setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        if (!UiUtils.isNormalClick(v)) {
            return;
        }
        Intent intent;
        switch (v.getId()) {
            case R.id.layout_device_lock:
                // 设备锁
                startActivity(new Intent(mContext, SecureSettingActivity.class));
                break;
            case R.id.layout_safety_password:
                // 密码
                intent = new Intent(mContext, SetPasswordActivity.class);
                if(coreManager.getSelf().getHavePassword() == 0){
                    intent.putExtra("from",SetPasswordActivity.SET_FROM_NEW);
                }else{
                    intent.putExtra("from",SetPasswordActivity.SET_FROM_UPDATE);
                }
                startActivity(intent);
                break;
            case R.id.layout_safety_phone:
                // 手机
                intent = new Intent(mContext, BandAndChangePhoneActivity.class);
                intent.putExtra("from","change");
                intent.putExtra("type","2");
                startActivity(intent);
                break;
            case R.id.layout_safety_wechat:
                // 微信
                if(coreManager.getSelf().getIsWXBand()==0){
                    WXEntryActivity.wxBand(this);
                }else{//已绑定微信
                    ToastUtil.showToast(mContext,getString(R.string.band_wechat_toast));
                }
                break;
            case R.id.layout_safety_qq:
                // QQ
                if(coreManager.getSelf().getIsQQBand()==0){
                    mIUiListener = new BaseUiListener();
                    //all表示获取所有权限
                    mTencent.login(SettingSafetyActivity.this, "all", mIUiListener);
                }else{//已绑定QQ
                    ToastUtil.showToast(mContext,getString(R.string.band_qq_toast));
                }
                break;
        }
    }

    /**
     * QQ登录授权回调
     */
    private class BaseUiListener implements IUiListener {

        @Override
        public void onComplete(Object response) {
            if (null == response) {
                ToastUtil.showToast(SettingSafetyActivity.this,"登录失败");
                return;
            }
            JSONObject jsonResponse = (JSONObject) response;
            if (null != jsonResponse && jsonResponse.length() == 0) {
                ToastUtil.showToast(SettingSafetyActivity.this, "登录失败");
                return;
            }
            doComplete((JSONObject)response);
        }

        protected void doComplete(JSONObject obj) {

            try {
                DialogHelper.showMessageProgressDialog(SettingSafetyActivity.this, "正在授权...");
                String openID = obj.getString("openid");
                String accessToken = obj.getString("access_token");
                String expires = obj.getString("expires_in");
                mTencent.setOpenId(openID);
                mTencent.setAccessToken(accessToken, expires);
                QQToken qqToken = mTencent.getQQToken();
                UserInfo mUserInfo = new UserInfo(getApplicationContext(), qqToken);
                mUserInfo.getUserInfo(new IUiListener() {
                    @Override
                    public void onComplete(Object response) {
                        //是一个json串response.tostring，直接使用gson解析就好
                        Log.e(TAG, "登录成功" + response.toString());
                        bandQQ(openID,response);

                    }

                    @Override
                    public void onError(UiError uiError) {
                        DialogHelper.dismissProgressDialog();
                        Log.e(TAG, "登录失败" + uiError.toString());
                    }

                    @Override
                    public void onCancel() {
                        DialogHelper.dismissProgressDialog();
                        Log.e(TAG, "登录取消");

                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onError(UiError e) {
            DialogHelper.dismissProgressDialog();
            ToastUtil.showToast(SettingSafetyActivity.this,"绑定失败");
        }

        @Override
        public void onCancel() {
            DialogHelper.dismissProgressDialog();
            ToastUtil.showToast(SettingSafetyActivity.this,"绑定取消");
        }
    }

    /**
     * QQ授权后请求服务器绑定
     * @param code QQ授权返回的openId
     * @param response QQ绑定返回的用户信息
     */
    private void bandQQ(String code, Object response) {

        JSONObject resultJson = (JSONObject)response;
        Map<String, String> params = new HashMap<>();
        params.put("loginInfo", code);
        params.put("type", Constants.LOGIN_QQ);
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("nickname",resultJson.optString("nickname"));
        params.put("sex",resultJson.optString("gender").equals("男") ? "1":"0");
        params.put("imgurl",resultJson.optString("figureurl_qq_1"));
        params.put("province",resultJson.optString("province"));
        params.put("city",resultJson.optString("city"));

        HttpUtils.get().url(coreManager.getConfig().THIRD_GET_BAND)
                .params(params)
                .build()
                .execute(new BaseCallback<LoginRegisterResult>(LoginRegisterResult.class) {

                    @Override
                    public void onResponse(ObjectResult<LoginRegisterResult> result) {
                        DialogHelper.dismissProgressDialog();
                        if (Result.checkSuccess(getApplicationContext(), result)) {
                            coreManager.getSelf().setIsQQBand(1);
                            coreManager.getSelf().setQqNickName(resultJson.optString("nickname"));
                            UserDao.getInstance().updateIsQQBand(coreManager.getSelf().getUserId(), 1);
                            UserDao.getInstance().updateQQNickName(coreManager.getSelf().getUserId(), resultJson.optString("nickname"));
                            updateUI();
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        finish();
                    }
                });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //QQ授权成功后会回调
        if (requestCode == com.tencent.connect.common.Constants.REQUEST_LOGIN ||
                requestCode == com.tencent.connect.common.Constants.REQUEST_APPBAR) {
            Tencent.onActivityResultData(requestCode,resultCode,data,mIUiListener);
            return;
        }
    }
}
